const { db } = require('../config/database');

class HealthData {
  // 添加健康数据
  static create(healthData) {
    const { user_id, data_type, value, unit, notes } = healthData;
    
    return new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO health_data (user_id, data_type, value, unit, notes) VALUES (?, ?, ?, ?, ?)',
        [user_id, data_type, value, unit, notes],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve({
              id: this.lastID,
              user_id,
              data_type,
              value,
              unit,
              notes,
              created_at: new Date().toISOString()
            });
          }
        }
      );
    });
  }

  // 获取用户所有健康数据
  static findAllByUserId(userId) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM health_data WHERE user_id = ? ORDER BY created_at DESC', [userId], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  // 获取用户特定类型的健康数据
  static findByUserIdAndType(userId, dataType) {
    return new Promise((resolve, reject) => {
      db.all(
        'SELECT * FROM health_data WHERE user_id = ? AND data_type = ? ORDER BY created_at DESC',
        [userId, dataType],
        (err, rows) => {
          if (err) {
            reject(err);
          } else {
            resolve(rows);
          }
        }
      );
    });
  }

  // 根据ID获取健康数据
  static findById(id) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM health_data WHERE id = ?', [id], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  // 更新健康数据
  static update(id, healthData) {
    const { value, unit, notes } = healthData;
    
    return new Promise((resolve, reject) => {
      db.run(
        'UPDATE health_data SET value = ?, unit = ?, notes = ? WHERE id = ?',
        [value, unit, notes, id],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes > 0);
          }
        }
      );
    });
  }

  // 删除健康数据
  static delete(id) {
    return new Promise((resolve, reject) => {
      db.run('DELETE FROM health_data WHERE id = ?', [id], function(err) {
        if (err) {
          reject(err);
        } else {
          resolve(this.changes > 0);
        }
      });
    });
  }
}

module.exports = HealthData; 